<template>
	<view>
		<view class="header">
			<view class="">
				<view class="">
					Hello,
				</view>
				<view class="">
					欢迎登录哇巴扎
				</view>
			</view>
		</view>
		<button open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber" :disabled="checked1.length==0">
			<view class="btn" :style="checked1.length==0?'background-color: #eeeeee;':''">
				手机号快捷登录
			</view>
		</button>
		<view class="" @click="back" style="text-align: center;margin: 10rpx;color: #6fe78d;">
			暂不登录
		</view>
		<view class="footer">
			<u-checkbox-group v-model="checked1">
				<u-checkbox activeColor="#FFC400" label=" " name="1"></u-checkbox>
				<text>请您阅读并同意</text>
				<text style="color: #FFC400;" @click="nav('/pagesB/xieyi1/xieyi1')">《隐私协议》</text>
				<text>和</text>
				<text style="color: #FFC400;" @click="nav('/pagesB/xieyi1/xieyi1')">《服务协议》</text>
			</u-checkbox-group>
		</view>
		
		
	</view>
</template>
<script>
	import graceChecker from '@/common/graceChecker';
	import home from '@/components/home/index'
	export default {
		components: {
			home
		},
		data() {
			return {
				submitDisabled: true,
				providerList: [],
				loginRes: {},
				pageroute: '',
				checked: 0,
				checked1: []
			};
		},

		async onLoad(option) {
			// #ifdef H5
			// 微信内置浏览器登录
			if (this.$jssdk.isWechat()) {
				let local = window.location.href; // 获取页面url
				let code = this.getUrlCode().code; // 截取code
				// 获取之前的code
				let oldCode = uni.getStorageSync('wanlshop:code');
				// 如果没有code，就去请求获取code
				if (code == null || code === '' || code == 'undefined' || code == oldCode) {
					let uri = encodeURIComponent(local);
					let page = this.$wanlshop.prePage().$mp.page;
					uni.setStorageSync('wanlshop:code', 0); // 设置旧的code为0，避免死循环
					window.location.href =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.$wanlshop.config('appid')}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=${encodeURIComponent(`/${page.route}?${this.$wanlshop.parseParams(page.options)}`)}#wechat_redirect`
				} else {
					let pageroute = this.getUrlCode().state; // 截取state
					uni.setStorageSync('wanlshop:code', code); // 保存最新code
					await uni.request({
						url: '/wanlshop/user/third',
						method: 'POST',
						data: {
							platform: 'h5_weixin',
							code: code,
							client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni.getStorageSync(
								"wanlshop:chat_client_id") : null
						},
						success: res => {
							this.$store.dispatch('user/login', res.data);
							this.$store.dispatch('cart/login');
							this.$store.dispatch('chat/get');
							uni.reLaunch({
								url: decodeURIComponent(pageroute)
							});
						}
					});
				}
			} else {
				let page = this.$wanlshop.prePage().$mp.page;
				this.pageroute = encodeURIComponent(`/${page.route}?${this.$wanlshop.parseParams(page.options)}`);
			}
			// 未来版本开发
			// this.providerList = [{
			// 	name: 'wlIcon-QQ',
			// 	platform: 'web_qq'
			// }];
			// #endif

			// 获取第三方登录
			// #ifndef H5
			let page = this.$wanlshop.prePage().$mp.page;
			this.pageroute = encodeURIComponent(`/${page.route}?${this.$wanlshop.parseParams(page.options)}`);
			uni.getProvider({
				service: 'oauth',
				success: (res) => {
					this.providerList = res.provider.map((value) => {
						let providerName = '';
						let platform = '';
						switch (value) {
							case 'weixin':
								providerName = 'wlIcon-WeChat';
								// #ifdef MP
								platform = 'mp_weixin';
								// #endif
								// #ifdef APP-PLUS
								platform = 'app_weixin';
								// #endif
								break;
							case 'qq':
								providerName = 'wlIcon-QQ'
								// #ifdef MP
								platform = 'mp_qq';
								// #endif
								// #ifdef APP-PLUS
								platform = 'app_qq';
								// #endif
								break;
							case 'sinaweibo':
								providerName = 'wlIcon-WeiBo'
								platform = 'app_weibo';
								break;
							case 'xiaomi':
								providerName = 'wlIcon-Xiaomi'
								platform = 'app_xiaomi';
								break;
							case 'apple':
								providerName = 'wlIcon-Apple'
								platform = 'apple';
								break;
						}
						return {
							id: value,
							name: providerName,
							platform: platform
						}
					});
				},
				fail: (error) => {
					console.log('获取登录通道失败', error);
				}
			});
			// #endif

			// 防止刷新登录态，uni.login code提前获取
			// #ifdef MP-WEIXIN
			uni.login({
				provider: 'weixin',
				success: res => {
					this.loginRes = res;
				},
				fail: err => {
					this.$wanlshop.msg(err.msg);
				}
			});
			// #endif
		},
		methods: {
			back(){
				uni.reLaunch({
					url:"/pages/index"
				})
			},
			nav(url) {
				uni.navigateTo({
					url
				})
			},
			CheckboxChange(e) {
				this.checked = e.detail.value;
			},
			// 第三方登录
			tologin(provider) {
				uni.showLoading({
					title: '登录中'
				});
				// #ifndef H5
				uni.login({
					provider: provider.id,
					// #ifdef MP-ALIPAY
					scopes: 'auth_user', //支付宝小程序需设置授权类型
					// #endif
					success: (loginRes) => {
						uni.request({
							url: '/wanlshop/user/third',
							method: 'POST',
							data: {
								platform: provider.platform,
								loginData: loginRes,
								client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni
									.getStorageSync("wanlshop:chat_client_id") : null
							},
							success: res => {
								uni.hideLoading();
								if (res.data.binding == 0) {
									this.$wanlshop.to(
										`/pages/user/auth/perfect?token=${res.data.token}&platform=${provider.platform}&url=${this.pageroute}`
									);
								} else {
									this.$store.dispatch('user/login', res.data);
									this.$store.dispatch('cart/login');
									this.$store.dispatch('chat/get');
									uni.reLaunch({
										url: decodeURIComponent(this.pageroute)
									});
								}
							}
						});
						// 隐藏键盘
						uni.hideKeyboard();
					},
					fail: err => {
						this.$wanlshop.msg(err.msg);
					}
				});
				// #endif
				// #ifdef H5
				uni.request({
					url: '/wanlshop/user/third_web',
					method: 'POST',
					data: {
						platform: provider.platform,
						client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni.getStorageSync(
							"wanlshop:chat_client_id") : null
					},
					success: res => {
						uni.hideLoading();
						this.$store.dispatch('user/login', res.data);
						this.$store.dispatch('cart/login');
						this.$store.dispatch('chat/get');
						// 返回页面
						uni.reLaunch({
							url: decodeURIComponent(this.pageroute)
						});
					}
				});
				// #endif
			},
			onKeyInput(e) {
				this.submitDisabled = false
			},
			// 号码登录，暂时支持微信小程序，后续版本逐渐开发
			async decryptPhoneNumber(e) {
				uni.login({
					provider: 'weixin',
					success: async res1 => {
						this.loginRes = res1;
						if (e.detail.errMsg != "getPhoneNumber:fail user deny") {
							await uni.request({
								url: '/wanlshop/user/phone',
								method: 'POST',
								data: {
									encryptedData: e.detail.encryptedData,
									iv: e.detail.iv,
									code: this.loginRes.code,
									client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni
										.getStorageSync(
											"wanlshop:chat_client_id") : null
								},
								success: res => {
									this.$store.dispatch('user/login', res.data);
									this.$store.dispatch('cart/login');
									// 返回页面
									uni.reLaunch({
										url: decodeURIComponent(this.pageroute)
									});
								}
							});
						}
					},
					fail: err => {
						this.$wanlshop.msg(err.msg);
					}
				});

			},
			// 账户登录
			formSubmit(e) {
				if (this.checked == 2) {
					//将下列代码加入到对应的检查位置
					//定义表单规则
					let rule = [{
						name: 'account',
						checkType: 'phoneno',
						errorMsg: '不是手机号码'
					}];
					//进行表单检查
					let formData = e.detail.value;
					let checkRes = graceChecker.check(formData, rule);
					// ..检查是否注册-没注册跳转注册
					if (checkRes) {
						uni.request({
							url: '/wanlshop/validate/check_mobile_exist',
							data: {
								mobile: formData.account
							},
							// 1.1.8升级
							complete: res => {
								if (res.res.code == 0) {
									uni.showModal({
										title: '提示',
										content: '账号不存在，是否注册？',
										success: (res) => {
											if (res.confirm) {
												this.$wanlshop.to(
													`register?mobile=${formData.account}&url=${this.pageroute}`
												);
											} else if (res.cancel) {
												console.log('取消');
											}
										}
									});
								} else {
									this.$wanlshop.to(`phone?mobile=${formData.account}&url=${this.pageroute}`,
										'none');
								}
							}
						});
					} else {
						if (formData.account) {
							this.$wanlshop.to(`name?name=${formData.account}&url=${this.pageroute}`, 'none');
						} else {
							this.$wanlshop.msg('请填写账号');
						}
					}
				} else {
					this.checked = 1;
					setTimeout(() => {
						this.checked = 0;
						this.$wanlshop.msg('请先同意用户协议和隐私保护声明');
						this.checked = ['2'];
					}, 300)
				}
			},
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				// this.winUrl = url;
				var theRequest = new Object();
				if (url.indexOf('?') != -1) {
					var str = url.substr(1);
					var strs = str.split('&');
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
					}
				}
				return theRequest;
			},
			register() {
				this.$wanlshop.to(`register?url=${this.pageroute}`);
			},
			help() {
				this.$wanlshop.to(`/pages/user/help?url=${this.pageroute}`);
			}
		}
	};
</script>
<style>
	page {
		background-color: white;
	}
</style>
<style scoped lang="scss">
	.footer {
		position: fixed;
		left: 0;
		bottom: 60rpx;
		font-size: 28rpx !important;
		display: flex;
		justify-content: center;
		width: 100vw;
	}

	.header {

		display: flex;
		align-items: center;
		font-size: 50rpx;
		font-weight: 600;
		margin: 100rpx 40rpx;
		color: #343434;

		image {
			width: 80rpx;
			height: 110rpx;
			margin-right: 30rpx;
		}
	}

	button {
		background-color: rgba(1, 1, 1, 0) !important;
		border: none !important;
	}

	button::before {
		border: none !important;
	}

	button::after {
		border: none !important;
	}

	.btn {
		color: white;
		background-color: rgb(7, 193, 96);
		margin: 30rpx;
		text-align: center;
		border-radius: 100px;
		font-size: 32rpx;
		padding: 12rpx;
	}
</style>